import { createContext, useContext } from "react";
import { useCallback } from "react";

import { useNavigate, useLocation } from "react-router-dom";
import { useSessionStorage } from "@mantine/hooks";
import { keys, delMany, clear } from "idb-keyval";

let PageTabManagementContext = createContext(null);
PageTabManagementContext.displayName = "[WITHWINGS]PageTabManagementContext";

function PageTabManagementContetProvider({ children }) {
  const navigate = useNavigate();
  const { pathname } = useLocation();

  const [pageTabs, setPageTabs] = useSessionStorage({
    key: "session-key",
    defaultValue: [],
  });

  const closeAll = useCallback(() => {
    setPageTabs([]);
    clear();
    navigate("/");
  }, [pageTabs]);

  const openPageTab = useCallback(
    (path, title) => {
      const existing = pageTabs.find((tab) => tab.path === path);

      if (!existing) {
        setPageTabs((tabs) => [...tabs, { path, title }]);
      } else {
      }
      navigate(path);
    },
    [pageTabs]
  );

  const closePageTab = useCallback(
    (path) => {
      let index = pageTabs.findIndex((tab) => tab.path === path);
      console.log("path:", path, "pathname", pathname);
      if (path !== pathname) {
        // 如果不是当前页签不用navigate
      } else if (pageTabs.length == 1) {
        // 如果只有一个页签， navigate至首页
        navigate("/");
      } else if (index === 0) {
        console.log("hey", pageTabs[1].path);
        // 如果是第一个页签， navigate到第二个
        navigate(pageTabs[1].path);
      } else {
        // 否则 navigate到前一个页签
        navigate(pageTabs[index - 1].path);
      }
      setPageTabs((pageTabs) => pageTabs.filter((tab) => tab.path !== path));

      //清空 tabby数据
      keys()
        .then((keys) => keys.filter((key) => key.startsWith(`[${path}]`)))
        .then(delMany);
    },
    [pageTabs, pathname]
  );

  const updatePageTabTitle = useCallback(
    (path, title) => {
      const existing = pageTabs.find((tab) => tab.path === path);
      if (existing) {
        existing.title = title;
      }
    },
    [pageTabs]
  );

  return (
    <PageTabManagementContext.Provider
      value={{
        pageTabs,
        openPageTab,
        closePageTab,
        closeAll,
        updatePageTabTitle,
      }}
    >
      {children}
    </PageTabManagementContext.Provider>
  );
}

function usePageTabManagementContext() {
  return useContext(PageTabManagementContext);
}

export { usePageTabManagementContext };

export default PageTabManagementContetProvider;
